package comment

import (
	"github.com/gin-gonic/gin"
	"savor_gin/controllers"
	. "savor_gin/errorType"
	"savor_gin/models"
	"strconv"
)

// 添加评论信息
func AddComment(c *gin.Context) {
	var comment models.Comments
	if err := c.ShouldBindJSON(&comment); err != nil {
		controllers.SendResp(c, ParamBindError, nil)
		return
	}
	if err := comment.Create(); err != nil {
		controllers.SendResp(c, DataBaseError, nil)
		return
	}
	controllers.SendResp(c, OK, comment)
}

// 更新评论信息
func UpdateCommentInfo(c *gin.Context) {
	commentId, err := strconv.Atoi(c.Param("commentId"))
	if err != nil {
		controllers.SendResp(c, ParamBindError, err)
		return
	}
	s := &models.Comments{CommentID: uint64(commentId)}
	if err := c.ShouldBind(s); err != nil {
		controllers.SendResp(c, ParamBindError, err)
		return
	}
	if err := s.Update(); err != nil {
		controllers.SendResp(c, DataBaseError, err)
		return
	}
	controllers.SendResp(c, OK, s)
}

// 删除评论信息
func DeleteComment(c *gin.Context) {
	// 通过动态URL传递参数
	commentId, err := strconv.Atoi(c.Query("commentId"))
	if err != nil {
		controllers.SendResp(c, ParamBindError, err)
		return
	}
	s := &models.Comments{CommentID: uint64(commentId)}
	if err := s.Delete(); err != nil {
		controllers.SendResp(c, DataBaseError, err)
		return
	}
	controllers.SendResp(c, OK, nil)
}

// 根据recipeId获取该食谱下的评论信息
func GetCommentByRecipeId(c *gin.Context) {
	recipeId, err := strconv.Atoi(c.Query("recipeId"))
	if err != nil {
		controllers.SendResp(c, ParamBindError, err)
		return
	}
	if s, err := models.GetCommentsByRecipeId(uint64(recipeId)); err != nil {
		controllers.SendResp(c, DataBaseError, err)
		return
	} else {
		controllers.SendResp(c, OK, s)
	}
}

// 查询个人的评论
func GetCommentListByUserId(c *gin.Context) {
	userId, err := strconv.Atoi(c.Param("userId"))
	if err != nil {
		controllers.SendResp(c, ParamBindError, err)
		return
	}
	if s, err := models.GetCommentsByUserId(uint64(userId)); err != nil {
		controllers.SendResp(c, DataBaseError, err)
		return
	} else {
		controllers.SendResp(c, OK, s)
	}
}

// 根据commentId获取评论信息
func GetCommentById(c *gin.Context) {
	commentId, err := strconv.Atoi(c.Query("commentId"))
	if err != nil {
		controllers.SendResp(c, ParamBindError, err)
		return
	}
	if s, err := models.GetCommentsById(uint64(commentId)); err != nil {
		controllers.SendResp(c, DataBaseError, err)
		return
	} else {
		controllers.SendResp(c, OK, s)
	}
}
